﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.ObjectModel;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;

namespace Gollie.Graph
{
	public class GraphDataSetCollection : Collection<GraphDataSet>
	{
		private double low = double.MaxValue;
		private double high = double.MinValue;

		internal double LowerBound
		{
			get { return this.low; }
			set { this.low = value; }
		}

		internal double UpperBound
		{
			get { return this.high; }
			set { this.high = value; }
		}

		internal string Url
		{
			get
			{
				if (this.Count == 0)
					return "";

				int cnt = 0;

				StringBuilder strLegend = new StringBuilder("chdl=", 64);
				StringBuilder strColor = new StringBuilder("chco=", 64);
				StringBuilder strData = new StringBuilder("chd=t:", 512);

				this.SetBounds();

				//low = 0;

				foreach (GraphDataSet dataSet in this)
				{
					if (cnt > 0)
					{
						strLegend.Append("|");
						strColor.Append(",");
						strData.Append("|");
					}

					strLegend.Append(dataSet.Legend);
					strColor.Append(Graph.StringColor(dataSet.Color));

					ValueCollection values = dataSet.ScaleToPercentage(this.low, this.high);

					int valueCount = 0;
					foreach (double value in values)
					{
						if (valueCount > 0)
						{
							strData.Append(",");
						}

						strData.Append(Graph.StringDouble(value));

						valueCount++;
					}

					cnt++;
				}

				StringBuilder url = new StringBuilder(strData.ToString(), 1024);
				url.Append("&");
				url.Append(strLegend.ToString());
				url.Append("&");
				url.Append(strColor.ToString());

				return url.ToString();
			}
		}

		private void SetBounds()
		{
			if (this.low < this.high) //already done.
				return;

			if (this.Count == 0)
			{
				this.low = 0;
				this.high = 0;

				return;
			}

			foreach (GraphDataSet dataSet in this)
			{
				double thisLow = dataSet.Values.LowerBound;
				double thisHigh = dataSet.Values.UpperBound;

				if (thisLow < this.low)
					this.low = thisLow;

				if (thisHigh > this.high)
					this.high = thisHigh;
			}
		}
	}
}